import { useUserStore } from '@/store'
import { router } from ''
// axios配置
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

const baseURL = 'https://consult-api.itheima.net/'

const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const store = useUserStore()
    if (store.userInfo?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.userInfo.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 10000) {
      ElMessage.error(res.data.message || '网络异常')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (err) => {
    // 处理登录失效
    if (err.response.status === 401) {
      const store = useUserStore()
      store.delUser()
      ElMessage.error('登录超时请重新登录！')
      return router.push({
        path: '/login',
        query: {
          // 方便重新登录后回到重新登录之前的页面
          returnUrl: router.currentRoute.value.fullPath
        }
      })
    }

    return Promise.reject(err)
  }
)

export type Data<T> = {
  code: string
  message: string
  data: T
}

const request = <T>(
  url: string,
  method: Method = 'get',
  submitData?: object
) => {
  return instance.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
  })
}

export { baseURL, instance, request }
